//
//  semYear.m
//  Gradekeeper0.2
//
//  Created by Ben Wu on 11/18/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//


#import "semYear.h"
#import "fileIO.h"
#import "SemTableView.h"
#define LEGAL	@"0123456789"

/*
 Sem Year will provide the necessary view and function for Year Creation
 User creates a new year by entering a legal length and interger ( 4 numbers), noncase sensitive.
 Alert box will appear if user tries to create a year more or less than 4 numbers long,
 or if a profile with the same year already exists.
 The user can choose to cancel the year, where an alert box will pop up to ask for cancel confirmation. 
 */

@implementation semYear
@synthesize segmentControl;

- (void)viewDidLoad {
	//Create a cancel button that lets the user cancel year creation
	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" 
																	 style:UIBarButtonItemStyleBordered 
																	target:self 
																	action:@selector(cancelCreate:)]; 
	self.navigationItem.leftBarButtonItem = cancelButton; 
	[cancelButton release]; 
	self.title = [NSString stringWithFormat:@"Create Semester"];
	
	semester = @"spring";
	
	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[inputYear release];
    [super dealloc];
}

- (void)cancelCreate:(id)sender {
	//If user confirms cancellation, current view will be popped and return to SemTableView
	UIAlertView *alert = [[UIAlertView alloc] 
						  initWithTitle:@"Cancel Confirmation" 
						  message:@"Are you sure you would like to cancel the action?" 
						  delegate:self
						  cancelButtonTitle:@"Yes" 
						  otherButtonTitles:nil]; 
	[alert addButtonWithTitle:@"No"];
    [alert show];
	
	[alert release];
	
} //cancelCreate

- (IBAction) btnClickMe_Clicked: (id) sender{
	NSString *year = inputYear.text;
	
	//Checks if year is at 4 intergers long, or if the year already exists.
	//If a year is created, the user will be alerted
	if ([year length] < 1 ){
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Invalid input" 
							  message:@"Please input the year" 
							  delegate:self
							  cancelButtonTitle:nil
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
	/*	
	} else if ([self profileExist:year]){
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Invalid input" 
							  message:@"The year you entered is already exist. Please reenter." 
							  delegate:self
							  cancelButtonTitle:nil
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		*/
		
	} else {
		[self writeToTextFile:self];
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Success" 
							  message:@"New sememester has been created" 
							  delegate:self
							  cancelButtonTitle:@"Ok" 
							  otherButtonTitles:nil]; 
		[alert show];
		[alert release];
	}
} //btnClickMe_Clicked

- (IBAction) chooseSemester:(id)sender {
	selectedSemester = [self.segmentControl selectedSegmentIndex];
	
	if (selectedSemester==0) {
		semester = @"spring";
	} else if (selectedSemester==1) { 
		semester = @"summer";
	} else if (selectedSemester==2){
		semester = @"fall";
	} else if (selectedSemester==3){
		semester = @"winter";
	}
	
	NSLog(@"%@", semester);
}

//If the alert is due to invalid input, do nothing
//Otherwise, the alert comes from cancellation request
//If cancellation is confirmed, pop to root view controller
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ([alertView.title isEqualToString:@"Invalid input"]){
	} else { 
		if (buttonIndex == 0) {
			[[self navigationController] popToRootViewControllerAnimated:YES];
		}
    }
} //alertView

//Takes the input entered and adds it to Course.txt <-- for now
//and creates a textfile with the same thing as the entered year.
-(IBAction) writeToTextFile:(id)sender{
	NSString *year = inputYear.text;
	NSString *toWrite = [NSString stringWithFormat:@"%@ %@", year, semester];
	[fileIO appendToFile:@"Course" :toWrite];
	
	[fileIO writeToFile:year:@""];	
	
} //writeToTextFile

//Checks if same year exists by comparing the entered year to data in Course.txt
- (BOOL) profileExist: (NSString *) desiredName{
	NSString *course = @"Course";
	NSString *tempsemList = nil;
	
	tempsemList = [[NSString alloc] initWithFormat:@"%@", [fileIO readFromFile:course]];
	
	NSArray *tempArray = [tempsemList componentsSeparatedByString: @":"];
	for (int y = 1; y < [tempArray count]; y ++){
		
		if ([[tempArray objectAtIndex:y] caseInsensitiveCompare: desiredName] == NSOrderedSame){
			
			return YES;
		} 			
	};	
	
	return NO;
} //profileExist


// allow only legal input ( 4 numbers)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	NSInteger insertDelta = string.length - range.length;
	
	if (textField.text.length + insertDelta > 4)
	{
		return NO; // the new string would be longer than MAX_LENGTH
	}
	else {
		NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet];
		NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
		
		return [string isEqualToString:filtered];
	}
} //textField

//Hides the keyboard after finishing text input (clicking done)
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	if (textField == inputYear) {
		[inputYear resignFirstResponder];
	}
	return YES;
} //textFieldShouldReturn

@end
